#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import requests
# 配置类
class HttpRequest:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.headers = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
          'User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv:29.0) Gecko/20100101 Firefox/29.0'}
    # 设置http头
    def set_header(self, headers):
        self.headers = headers
    # 封装HTTP GET请求方法
    def get(self, url, params):
        url = "http://"+self.host+":"+self.port+url
        try:
            print("get request begin-----------------")
            print("url:" + url)
            print("params:")
            print(params)
            r = requests.get(url, params=eval(params), headers=self.headers)
            r.encoding = 'UTF-8'
            print("response" + r.text)
            print("----------------- request end")
            return r.text
        except Exception:
            print('no json data returned')
            return {}
    # 封装HTTP POST请求方法,支持上传图片
    def post(self, url, data=None, files=None):
        data = eval(data)
        url = 'http://' + self.host + ':' + str(self.port)+url
        print("post request begin-----------------")
        print("url:" + url)
        print("params:" )
        print( data)
        r = requests.post(url, files=files, data=data)
        print("response"+r.text)
        print("----------------- request end")
        json_response = r.text
        return json_response

    def postBody(self,url,data=None):
        url = 'http://' + self.host + ':' + str(self.port) + url

        headers = {'Content-Type': 'application/json','User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv:29.0) Gecko/20100101 Firefox/29.0'}
        print("post request begin-----------------")
        print("url:" + url)
        print("params:")
        print(data)
        r = requests.post(url,json=json.loads(data),headers=headers)
        print("response" + r.text)
        print("----------------- request end")
        return r.text